package com.hhh.bigevent.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hhh.bigevent.pojo.Result;
import com.hhh.bigevent.pojo.UserDO;
import com.hhh.bigevent.utils.JwtUtil;
import com.hhh.bigevent.utils.Md5Util;
import com.hhh.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author hehehe
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$", message = "用户名长度应在5-16位") @RequestParam("username") String username,
                           @Pattern(regexp = "^\\S{5,16}$", message = "密码长度应在5-16位") @RequestParam("password") String password) {
        UserDO userDO = new UserDO();
        userDO.setUsername(username);
        UserDO selectOne = userDO.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(StringUtils.isNotEmpty(username), UserDO::getUsername, username));
        if (ObjectUtils.isNotNull(selectOne)) {
            return Result.error("用户名已存在！");
        }
        userDO.setPassword(Md5Util.getMD5String(password)).setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now());
        boolean insert = userDO.insert();
        if (insert) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$", message = "用户名长度应在5-16位") @RequestParam("username") String username,
                        @Pattern(regexp = "^\\S{5,16}$", message = "密码长度应在5-16位") @RequestParam("password") String password) {
        UserDO userDO = new UserDO().selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username).eq(UserDO::getPassword, Md5Util.getMD5String(password)));
        if (ObjectUtils.isNotNull(userDO)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", userDO.getId());
            map.put("username", username);
            String token = JwtUtil.genToken(map);
            redisTemplate.opsForValue().set(token, token, 7, TimeUnit.DAYS);
            return Result.success(token);
        }
        return Result.error("账号或密码错误！");
    }

    @GetMapping("/userInfo")
    public Result userInfo(@RequestHeader(value = "Authorization") String authorization) {
        Map<String, Object> map = JwtUtil.parseToken(authorization);
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        UserDO userDO = new UserDO();
        userDO.setUsername(username).setPassword(password);
        UserDO selectOne = userDO.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(StringUtils.isNotEmpty(username), UserDO::getUsername, username));
        if (ObjectUtils.isNotNull(selectOne)) {
            return Result.success(selectOne);
        }
        return Result.error("未登录！");
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated UserDO userDO) {
        boolean b = userDO.setUpdateTime(LocalDateTime.now()).updateById();
        return Result.success(b);
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        boolean b = new UserDO().setId(ThreadLocalUtil.getUserId()).setUserPic(avatarUrl).setUpdateTime(LocalDateTime.now()).updateById();
        return Result.success(b);
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map, @RequestHeader("Authorization") String token) {
        String oldPwd = map.get("old_pwd");
        String rePwd = map.get("re_pwd");
        String newPwd = map.get("new_pwd");
        if (StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(rePwd) || StringUtils.isEmpty(newPwd)) {
            return Result.error("原密码、新密码、确认新密码都不能为空！");
        }
        UserDO aDo = new UserDO().setId(ThreadLocalUtil.getUserId()).selectById();
        if (!aDo.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码输入错误！");
        }
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次输入的密码不一致！");
        }
        if (oldPwd.equals(newPwd)) {
            return Result.error("原密码不能与新密码相同！");
        }
        boolean b = new UserDO().setPassword(Md5Util.getMD5String(newPwd)).setId(ThreadLocalUtil.getUserId()).setUpdateTime(LocalDateTime.now()).updateById();
        redisTemplate.opsForValue().getOperations().delete(token);
        return Result.success(b);
    }
}
